import axios from "axios";
import qs from 'qs';
import {ElMessage} from 'element-plus'  //信息提示控件

//设置基础URL
axios.defaults.baseURL = 'http://localhost:8080/api';

//拦截所有的请求，添加请求header
axios.interceptors.request.use(
    function(config){
        if(config.method == 'post'){
            config.headers = {'Content-Type': "application/x-www-form-urlencoded"};
        }
        config.data = qs.stringify(config.data);
        if(localStorage.getItem('token')){
            config.headers['Authorization'] = localStorage.getItem('token');
        }
        return config;
    },
    function(error){
        Promise.reject(error);
    });

//拦截所有的响应，添加响应的通用代码
axios.interceptors.response.use(
    function(response){
        if(response.status == 200){     //服务器正常响应内容
            let result = response.data;
            console.log("index.js里console的数据")
            console.log(result)
            if(result.code === '0'){    //业务执行正确
                if(result.msg){     //如果服务端发送了提示信息，那么就在客户端显示这个提示信息
                    ElMessage({type: 'success', message: result.msg});
                }
                return Promise.resolve(result.data);
            }
            if(result.code === '1'){    
                if(result.msg){     
                    ElMessage.error(result.msg);
                }
                return Promise.resolve(result.data);
            }
            return Promise.resolve(result);
        }
        return Promise.reject(response);
    },
    function(error){
        ElMessage({type: 'error', message: `错误信息：${error}`});
        return Promise.reject(error);
    });

//导出封装后的对象
//注意：封装后的对象需要在main.js中重新引入
export default axios;